<?php

/*
  Plugin Name: Codeko Sliders
  Plugin URI: http://codeko.com/productos/software-libre/postslider/
  Description: Widgets, template tag and shortcode to show a variety of sliders using AnythingSlider (v1.5.9).
  Version: 0.6
  Author: Codeko Informática
  Author URI: http://codeko.com
  License: GPL2
 */
//GLOBAL DATA
//Used to avoid infine loops when a post inside a slider has a slider with the same post in it
$is_inside_slider = false;
//Count to define the auto-id in the shorcode slider. Avoid js errors if more
//than one slider is used in the same page/post
$sliders_count = 0;

//Load the languages
add_action('init', 'codeko_post_slider_load_plugin_textdomain');

function codeko_post_slider_load_plugin_textdomain() {
    $plugin_dir = basename(dirname(__FILE__));
    load_plugin_textdomain('codeko_post_slider', null, $plugin_dir . "/languages");
}

//Register widget
add_action('widgets_init', 'codeko_slider_load_widgets');

function codeko_slider_load_widgets() {
    register_widget('CodekoPostSlider');
    register_widget('CodekoImageSlider');
    register_widget('CodekoGenericSlider');
}

function add_plugin_links($links, $file) {

    if ($file == plugin_basename(__FILE__)) {
        $links[] = '<a href="http://code.google.com/p/codeko-wp-sliders/w/list">' . __('Get Help', 'codeko_post_slider') . '</a>';
        $links[] = '<a href="http://proloser.github.com/AnythingSlider/">' . __('AnythingSlider Help', 'codeko_post_slider') . '</a>';
        $links[] = '<a href="http://code.google.com/p/codeko-wp-sliders/">' . __('Contribute', 'codeko_post_slider') . '</a>';
    }
    return $links;
}

add_filter('plugin_row_meta', 'add_plugin_links', 10, 2);

/**
 * Load needed media (js and css)
 */
function codeko_slider_register_media() {
    if (is_admin ())
        return;
    wp_enqueue_script('anythingslider', plugins_url('/ProLoser-AnythingSlider/js/jquery.anythingslider.min.js', __FILE__), array('jquery'));
    wp_enqueue_script('anythingslider_fx', plugins_url('/ProLoser-AnythingSlider/js/jquery.anythingslider.fx.min.js', __FILE__), array('jquery', 'anythingslider'));
    wp_enqueue_style('anythingslider', plugins_url('/ProLoser-AnythingSlider/css/anythingslider.css', __FILE__));
    wp_enqueue_script('codeko_posts_slider', plugins_url('/js/codeko_post_slider.js', __FILE__), array('jquery', 'anythingslider'));
}

/**
 * Gets de js script with the jQuery call to anythingSlider
 * @return <type>
 */
function jQuery_call($sid, $slider_config, $custom_theme=null) {
    global $sliders_count;
    $slider_config_name = 'codeko_slider_config_' . $sliders_count;
    $data = '<script type="text/javascript">';
    $data.='var ' . $slider_config_name . '={' . $slider_config . '};';
    if ($custom_theme) {
        $data.=$slider_config_name . '.themeDirectory="' . get_bloginfo('template_url') . $custom_theme . '";';
    } else {
        $data.=$slider_config_name . '.themeDirectory="' . plugins_url('/slider/css/', __FILE__) . 'theme-{themeName}.css";';
    }
    $data.='codeko_post_slider_ini("' . $sid . '",' . $slider_config_name . ');</script>';
    $sliders_count++;
    return $data;
}

/**
 * Alias function to be used in themes. Call the shortcode function
 * @param <type> $atts
 * @param <type> $slider_config
 * @return <type>
 */
function codeko_posts_slider($atts, $slider_config=null) {
    return codeko_slider_shortcode($atts, $slider_config);
}

/**
 * Shortcode
 * @global <type> $post
 * @global int $more
 * @global bool $is_inside_slider
 * @global int $sliders_count
 * @param <type> $atts
 * @param <type> $content
 * @return <type>
 */
function codeko_slider_shortcode($atts, $content=null) {
    global $post, $more, $is_inside_slider, $sliders_count;
    //If we are inside a slider don't return anything to prevent infinite loops
    if ($is_inside_slider) {
        return "";
    }
    $old_post = $post;
    //Set we are inside a slider
    $is_inside_slider = true;
    codeko_slider_register_media();
    $atts = shortcode_atts(array(
                'id' => 'shortcode',
                'number_of_posts' => 5,
                'category_id' => 0,
                'width' => null,
                'custom_query' => null,
                'height' => null,
                'self_exclude' => 1,
                'theme' => "default",
                'content_selector' => null,
                'custom_renderer' => false,
                'show_images' => null,
                'isize' => 'medium'
                    ), $atts);
    extract($atts);
    $post_id = $sliders_count;
    if ($post) {
        $post_id = $post->ID;
    }
    $sid = "cslider_" . $post->ID;
    ob_start();
    if ($show_images) {
        show_image_slider($sid, $instance);
    } else if ($content_selector) {
        activate_slider($content_selector, $instance);
    } else {
        show_posts_slider($sid, $instance);
    }
    $is_inside_slider = false;
    $post = $old_post;
    return ob_get_clean();
}

add_shortcode('post_slider', 'codeko_slider_shortcode');

function show_posts_slider($sid, $instance) {
    global $post, $more, $is_inside_slider;
    $old_post = $post;
    $args = array();
    if ($instance["self_exclude"] && $post) {
        $args['exclude'] = $post->ID;
    }
    if ($instance["number_of_posts"]) {
        $args['numberposts'] = $instance["number_of_posts"];
    }
    if ($instance["category_id"]) {
        $args["category"] = $instance["category_id"];
    }
    if ($instance["custom_query"]) {
        $args = $instance["custom_query"];
    }
    echo '<div class="slider_container"  style="display:none"> <ul id="' . $sid . '">';
    $myposts = get_posts($args);
    foreach ($myposts as $post) {
        setup_postdata($post);
        echo '<li>';
        if ($instance["custom_renderer"] && function_exists($instance["custom_renderer"])) {
            $instance["custom_renderer"]($post);
        } else {
            $permalink = get_permalink( );
            $post_title = the_title('', '', false);
            echo '<h4 class="slider_title"><a href="' . $permalink . '" title="' . $post_title . '">' . $post_title . '</a></h4>';
            $more = 0;
            the_content(__('More...', 'codeko_post_slider'));
        }
        echo '</li>';
    }
    echo '</ul></div>';
    $post = $old_post;
    activate_slider("#" . $sid, $instance);
}

function show_image_slider($sid, $instance) {
    global $post, $is_inside_slider;
    $old_post = $post;
    echo '<div class="slider_container"  style="display:none"> <ul id="' . $sid . '">';
    $img_ids_pre = explode(",", $instance["show_images"]);
    $img_ids = array();
    foreach ($img_ids_pre AS $img_data) {
        $img_data = trim($img_data);
        $pos = strpos($img_data, "-");
        if ($pos === false) {
            $img_ids[] = $img_data;
        } else {
            list($img_min, $img_max) = explode("-", $img_data);
            $img_min = (int) $img_min;
            $img_max = (int) $img_max;
            if ($img_min < $img_max) {
                for (; $img_min <= $img_max; $img_min++) {
                    $img_ids[] = $img_min;
                }
            }
        }
    }
    foreach ($img_ids AS $img_id) {
        $image_attributes = wp_get_attachment_image_src($img_id, $instance['isize']);
        if ($image_attributes) {
            if ($instance["custom_renderer"] && function_exists($instance["custom_renderer"])) {
                $instance["custom_renderer"]($image_attributes);
            } else {
                echo '<li><img src="' . $image_attributes[0] . '" width="' . $image_attributes[1] . '" height="' . $image_attributes[2] . '"></li>';
            }
        }
    }
    echo '</ul></div>';
    $post = $old_post;
    activate_slider("#" . $sid, $instance);
}

function activate_slider($sid, $instance) {
    if (!$instance["height"]) {
        $instance["height"] = "null";
    }
    if (!$instance["width"]) {
        $instance["width"] = "null";
    }

    if ($instance["custom_theme"]) {
        $instance["theme"] = 'custom';
    }
    $slider_config = 'theme:"' . $instance["theme"] . '",startText:"' . __("Start", 'codeko_post_slider') . '",stopText:"' . __("Stop", 'codeko_post_slider') . '",resizeContents: true,width:"' . $instance["width"] . '",height: "' . $instance["height"] . '"';
    if (trim($instance["slider_config"])) {
        $slider_config = $instance["slider_config"];
    }
    echo jQuery_call($sid, $slider_config, $instance["custom_theme"]);
}

/**
 * Widgets
 */

/**
  Generic widget class
 * */
class CodekoSliderWidget extends WP_Widget {

    function echo_field($instance, $name, $title, $help=null) {
        echo '<p>';
        echo '<label for="' . $this->get_field_id($name) . '">' . __($title) . ':</label>';
        echo '<input class="widefat" type="text" id="' . $this->get_field_id($name) . '" name="' . $this->get_field_name($name) . '" value="' . $instance[$name] . '" />';
        if ($help) {
            echo "<small>" . $help . "</small>";
        }
        echo '</p>';
    }

    function echo_textarea($instance, $name, $title, $help=null) {
        echo '<p>';
        echo '<label for="' . $this->get_field_id($name) . '">' . __($title) . ':</label>';
        echo '<textarea class="widefat" id="' . $this->get_field_id($name) . '" name="' . $this->get_field_name($name) . '" >' . $instance[$name] . '</textarea>';
        if ($help) {
            echo "<small>" . $help . "</small>";
        }
        echo '</p>';
    }

    function echo_select($instance, $name, $title, $items, $help=null) {
        echo '<p>';
        echo '<label for="' . $this->get_field_id($name) . '">' . __($title) . ':</label>';
        echo '<select class="widefat" id="' . $this->get_field_id($name) . '" name="' . $this->get_field_name($name) . '" >';
        foreach ($items AS $value => $option_name) {
            echo '<option value="' . $value . '" ' . ($value == $instance[$name] ? "selected" : "") . '>' . $option_name . '</option>';
        }
        echo '</select>';
        if ($help) {
            echo "<small>" . $help . "</small>";
        }
        echo '</p>';
    }

    function echo_advanced_config($instance, $show_query_config=true, $show_renderer_config=true) {
        echo '<div class="widget">
            <div class="widget-top">
                <div class="widget-title-action">
                    <a href="#" class="widget-action hide-if-no-js"></a>
                </div>
                <div class="widget-title"><h4>' . __("Advanced") . '<span class="in-widget-title"></span></h4></div>
            </div>
            <div class="widget-inside">';
        $this->echo_textarea($instance, 'slider_config', __('Slider config', 'codeko_post_slider'), __('Custom slider\'s configuration, replaces slider width and height config.', 'codeko_post_slider'));
        $this->echo_field($instance, 'custom_query', __('Custom query', 'codeko_post_slider'), __('Custom get_posts() query, replaces category filter and number of posts.', 'codeko_post_slider'));
        $this->echo_field($instance, 'custom_renderer', __('Custom renderer', 'codeko_post_slider'), __('Template funcion name to print each post.', 'codeko_post_slider'));
        $this->echo_field($instance, 'custom_theme', __('Custom Theme', 'codeko_post_slider'), __('CSS file in your template. The path must be relative to your template folder and must start with "/".', 'codeko_post_slider'));
        echo '</div></div>';
    }

    function get_themes() {
        return array("default" => __("Default", 'codeko_post_slider'),
            "cs-portfolio" => __("CS-Portfolio", 'codeko_post_slider'),
            "construction" => __("Construction", 'codeko_post_slider'),
            "metallic" => __("Metallic", 'codeko_post_slider'),
            "minimalist-round" => __("Minimalist round", 'codeko_post_slider'),
            "minimalist-square" => __("Minimalist square", 'codeko_post_slider'),
            "custom" => __("Custom Theme (Set in advanced configuration)", 'codeko_post_slider'));
    }

}

/**
 * Widget to show a slider of posts
 */
class CodekoPostSlider extends CodekoSliderWidget {

    function CodekoPostSlider() {
        codeko_slider_register_media();
        $widget_ops = array('classname' => 'codeko_post_slider', 'description' => __('Widget to show a slider with the last posts of a category.', 'codeko_post_slider'));
        $control_ops = array('id_base' => 'codeko_post_slider_widget', 'width' => 255);
        $this->WP_Widget('codeko_post_slider_widget', __('Codeko Post Slider', 'codeko_post_slider'), $widget_ops, $control_ops);
    }

    function widget($args, $instance) {
        global $post, $more, $is_inside_slider;
        if ($is_inside_slider) {
            return;
        }
        $is_inside_slider = true;
        extract($args);
        $title = apply_filters('widget_title', $instance['title']);
        $sid = "cslider_" . $widget_id;
        echo $before_widget;
        if ($title) {
            echo $before_title . $title . $after_title;
        }
        show_posts_slider($sid, $instance);
        echo $after_widget;
        $is_inside_slider = false;
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['width'] = strip_tags($new_instance['width']);
        $instance['height'] = strip_tags($new_instance['height']);
        $instance['category_id'] = strip_tags($new_instance['category_id']);
        $instance['number_of_posts'] = strip_tags($new_instance['number_of_posts']);
        $instance['slider_config'] = strip_tags($new_instance['slider_config']);
        $instance['custom_query'] = strip_tags($new_instance['custom_query']);
        $instance['custom_renderer'] = strip_tags($new_instance['custom_renderer']);
        $instance['theme'] = strip_tags($new_instance['theme']);
        $instance['custom_theme'] = strip_tags($new_instance['custom_theme']);
        $instance['self_exclude'] = intval($new_instance['self_exclude']);
        return $instance;
    }

    function form($instance) {
        $defaults = array('title' => '', 'width' => 300, 'height' => 350,
            'category_id' => 0, 'number_of_posts' => 5, 'self_exclude' => 1,
            'slider_config' => '', 'custom_query' => '', 'custom_renderer' => '',
            'theme' => 'default');
        $instance = wp_parse_args((array) $instance, $defaults);
        $this->echo_field($instance, 'title', __('Title', 'codeko_post_slider'));
        $this->echo_field($instance, 'width', __('Slider width', 'codeko_post_slider'));
        $this->echo_field($instance, 'height', __('Slider height', 'codeko_post_slider'));
        $this->echo_field($instance, 'number_of_posts', __('Number of posts to show', 'codeko_post_slider'));
        echo '<p>';
        echo '<label for="' . $this->get_field_id('category_id') . '">' . __('Category', 'codeko_post_slider') . ':</label>';
        $args = array('hierarchical' => 1,
            'name' => $this->get_field_name('category_id'),
            'id' => $this->get_field_id('category_id'),
            'show_option_all' => __("All", 'codeko_post_slider'),
            'hide_empty' => 0,
            'class' => "widefat",
            'selected' => $instance['category_id']);
        wp_dropdown_categories($args);
        $this->echo_select($instance, 'theme', __('Theme', 'codeko_post_slider'), $this->get_themes());
        $this->echo_select($instance, 'self_exclude', __('Self exclude', 'codeko_post_slider'), array(1 => __("Yes", 'codeko_post_slider'), 0 => __("No", 'codeko_post_slider')), __("If auto exclude is Yes the current post (if any) does not show in the slider", 'codeko_post_slider'));
        echo '</p>';
        $this->echo_advanced_config($instance);
    }

}

/**
 * Widget to show a slider of images
 */
class CodekoImageSlider extends CodekoSliderWidget {

    function CodekoImageSlider() {
        codeko_slider_register_media();
        $widget_ops = array('classname' => 'codeko_image_slider', 'description' => __('Widget to show a slider with the specified images.', 'codeko_post_slider'));
        $control_ops = array('id_base' => 'codeko_image_slider_widget', 'width' => 255);
        $this->WP_Widget('codeko_image_slider_widget', __('Codeko Image Slider', 'codeko_post_slider'), $widget_ops, $control_ops);
    }

    function widget($args, $instance) {
        global $post, $more, $is_inside_slider;
        if ($is_inside_slider) {
            return;
        }
        $is_inside_slider = true;
        extract($args);
        $title = apply_filters('widget_title', $instance['title']);
        $sid = "cslider_" . $widget_id;
        echo $before_widget;
        if ($title) {
            echo $before_title . $title . $after_title;
        }
        show_image_slider($sid, $instance);
        echo $after_widget;
        $is_inside_slider = false;
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['width'] = strip_tags($new_instance['width']);
        $instance['height'] = strip_tags($new_instance['height']);
        $instance['slider_config'] = strip_tags($new_instance['slider_config']);
        $instance['custom_renderer'] = strip_tags($new_instance['custom_renderer']);
        $instance['show_images'] = strip_tags($new_instance['show_images']);
        $instance['theme'] = strip_tags($new_instance['theme']);
        $instance['custom_theme'] = strip_tags($new_instance['custom_theme']);
        $instance['isize'] = strip_tags($new_instance['isize']);
        return $instance;
    }

    function form($instance) {
        $defaults = array('title' => '', 'width' => 300, 'height' => 350,
            'slider_config' => '', 'custom_renderer' => '',
            'show_images' => '', 'isize' => '',
            'theme' => 'default');
        $instance = wp_parse_args((array) $instance, $defaults);
        $this->echo_field($instance, 'title', __('Title', 'codeko_post_slider'));
        $this->echo_field($instance, 'width', __('Slider Width', 'codeko_post_slider'));
        $this->echo_field($instance, 'height', __('Slider Height', 'codeko_post_slider'));
        $this->echo_select($instance, 'isize', __('Image size', 'codeko_post_slider'), $this->get_image_sizes());
        $this->echo_field($instance, 'show_images', __('Images', 'codeko_post_slider'), __('Put image IDs separated by comma or dash for ranges (1,2,10-20 for example). The images must be from the multimedia gallery.', 'codeko_post_slider'));
        $this->echo_select($instance, 'theme', __('Theme', 'codeko_post_slider'), $this->get_themes());
        $this->echo_advanced_config($instance, false, true);
    }

    function get_image_sizes() {
        return array("thumbnail" => __("Thumbnail", 'codeko_post_slider'),
            "medium" => __("Medium", 'codeko_post_slider'),
            "large" => __("Large", 'codeko_post_slider'),
            "full" => __("Full", 'codeko_post_slider'));
    }

}

/**
 * Widget to convert a list to a slider
 */
class CodekoGenericSlider extends CodekoSliderWidget {

    function CodekoGenericSlider() {
        codeko_slider_register_media();
        $widget_ops = array('classname' => 'codeko_generic_slider', 'description' => __('Widget to show a slider for existing content.', 'codeko_post_slider'));
        $control_ops = array('id_base' => 'codeko_generic_slider_widget', 'width' => 255);
        $this->WP_Widget('codeko_generic_slider_widget', __('Codeko Generic Slider', 'codeko_post_slider'), $widget_ops, $control_ops);
    }

    function widget($args, $instance) {
        global $post, $more, $is_inside_slider;
        if ($is_inside_slider) {
            return;
        }
        $is_inside_slider = true;
		extract($args);
		echo $before_widget;
        activate_slider($instance["content_selector"], $instance);
		echo $after_widget;
        $is_inside_slider = false;
    }

    function update($new_instance, $old_instance) {
        $instance = $old_instance;
        $instance['width'] = strip_tags($new_instance['width']);
        $instance['height'] = strip_tags($new_instance['height']);
        $instance['slider_config'] = strip_tags($new_instance['slider_config']);
        $instance['content_selector'] = strip_tags($new_instance['content_selector']);
        $instance['theme'] = strip_tags($new_instance['theme']);
        $instance['custom_theme'] = strip_tags($new_instance['custom_theme']);
        return $instance;
    }

    function form($instance) {
        $defaults = array('width' => 300, 'height' => 350,
            'slider_config' => '', 'theme' => 'default', 'content_selector' => '',
            'custom_theme' => '');
        $instance = wp_parse_args((array) $instance, $defaults);
        $this->echo_field($instance, 'width', __('Slider Width', 'codeko_post_slider'));
        $this->echo_field($instance, 'height', __('Slider Height', 'codeko_post_slider'));
        $this->echo_field($instance, 'content_selector', __('jQuery selector.', 'codeko_post_slider'), __('Put the jQuery selector for the element whom will be converted into a slider.', 'codeko_post_slider'));
        $this->echo_select($instance, 'theme', __('Theme', 'codeko_post_slider'), $this->get_themes());
        $this->echo_advanced_config($instance, false, false);
    }

}

?>
